<template>
	<div class="container">
		<svg :width="svgWidth" :height="svgHeight" :viewBox="`0 0 ${svgWidth} ${svgHeight}`">
			<path :d="loadpathData" fill="none" stroke="#2196f3" stroke-width="2" />
			<path v-if="pathPoints.length" :d="pathData" fill="none" stroke="#199f33" stroke-width="2" />
			<!-- 点位显示 -->
			<g v-for="(point, index) in points" :key="index" @click="selectPoint(point)" class="point-group">
				<!-- 呼吸效果背景 -->
				<circle :cx="point.x" :cy="point.y" r="15" class="point-circle"
					:class="{'start-point': isStartPoint(point),'end-point': isEndPoint(point)}" />
				<!-- 图标 -->
				<image :x="point.x - 10" :y="point.y - 10" :width="20" :height="20"
					:xlink:href="getIconPath(point.pointType)" class="point-icon" />
				<!-- 文本标签 -->
				<text :x="point.x + 15" :y="point.y - 15" class="point-label">
					{{ point.pointName }}
				</text>
			</g>
		</svg>
		<!-- 选中点位信息展示 -->
		<div v-if="selectedPoint" class="info-card" :style="{left: pos.x + 'px',top: pos.y + 'px'}">
			<div class="header" @mousedown="startDrag">
				<h3>点位详细信息 (拖动我)</h3>
			</div>
			<div class="content">

				<!-- 当前选中信息 -->
				<section class="current-point">
					<h4>当前点位</h4>
					<p>ID: {{ selectedPoint.id }}</p>
					<p>名称: {{ selectedPoint.pointName }}</p>
					<!-- 已选信息 -->
					<section class="selected-info">
						<div v-if="startPoint" class="selected-item">
							<el-tag type="success" size="small">起点</el-tag>
							<span>{{ startPoint.pointName }}</span>
						</div>
						<div v-if="endPoint" class="selected-item">
							<el-tag type="danger" size="small">终点</el-tag>
							<span>{{ endPoint.pointName }}</span>
						</div>
					</section>
					<!-- 操作按钮 -->
					<div class="action-buttons">
						<el-button type="success" plain @click="setAsStart">
							<template #icon>
								<Location />
							</template>
							设为起点
						</el-button>
						<el-button type="danger" plain @click="setAsEnd">
							<template #icon>
								<Place />
							</template>
							设为终点
						</el-button>
					</div>
				</section>
				<div class="action-group">
					<el-button type="primary" :disabled="!startPoint || !endPoint || isLoading"
						:class="{ 'highlight-button': startPoint && endPoint }" @click="handlePathPlanning">
						{{ isLoading ? '规划中...' : '开始路径规划' }}
					</el-button>
					<el-button v-if="startPoint || endPoint" type="info" @click="clearPoints" plain>
						清空起终点
					</el-button>
					<el-button v-if="isLoading" type="danger" @click="cancelPathPlanning" class="cancel-button">
						取消规划
					</el-button>
				</div>

			</div>
		</div>

	</div>

</template>

<script setup>
	import {
		ref,
		reactive,
		onMounted,
		computed,
		onUnmounted
	} from 'vue';
	import {
		ElMessage
	} from 'element-plus';
	import {
		wcao,
		post,
		rgvpost
	} from "@/http";
	import axios from 'axios';
	import './css/zhi0225.css';
	import {
		Location,
		Place
	} from '@element-plus/icons-vue'

	// 导入图片（将你的图片放在public/icons目录下）
	const iconMap = {
		'CAR': '/icons/car.svg',
		'WAREHOUSE': '/icons/ku.svg',
		'TRANSFER': '/icons/zhuan.svg',
		'DEFAULT': '/icons/default.svg'
	};
	// 新增图标获取方法
	const getIconPath = (type) => {
		return iconMap[type] || iconMap.DEFAULT;
	};
	// SVG画布尺寸
	const svgWidth = ref(window.innerWidth);
	const svgHeight = ref(window.innerHeight);
	const points = ref([]);
	const selectedPoint = ref(null);
	const startPoint = ref(null);
	const endPoint = ref(null);
	const pathPoints = ref([]);
	const isLoading = ref(false);
	const abortController = ref(null);
	// 新增拖动相关状态
	const pos = ref({
		x: 20,
		y: 20
	});
	const dragging = ref(false);
	const startX = ref(0);
	const startY = ref(0);
	const initialPos = ref({
		x: 0,
		y: 0
	});

	// 计算属性
	const isCurrentStart = computed(() =>
		selectedPoint.value?.id === startPoint.value?.id
	)

	const isCurrentEnd = computed(() =>
		selectedPoint.value?.id === endPoint.value?.id
	)
	// 方法
	const isStartPoint = (point) =>
		point.id === startPoint.value?.id

	const isEndPoint = (point) =>
		point.id === endPoint.value?.id
	// 窗口尺寸处理
	const handleResize = () => {
		svgWidth.value = window.innerWidth;
		svgHeight.value = window.innerHeight;
	};
	const startDrag = (e) => {
		dragging.value = true;
		startX.value = e.clientX;
		startY.value = e.clientY;
		initialPos.value = {
			...pos.value
		};

		// 添加全局事件监听
		document.addEventListener('mousemove', onDrag);
		document.addEventListener('mouseup', stopDrag);
	};
	const onDrag = (e) => {
		if (!dragging.value) return;

		const dx = e.clientX - startX.value;
		const dy = e.clientY - startY.value;

		pos.value = {
			x: initialPos.value.x + dx,
			y: initialPos.value.y + dy
		};
	};

	const stopDrag = () => {
		dragging.value = false;
		document.removeEventListener('mousemove', onDrag);
		document.removeEventListener('mouseup', stopDrag);
	};
	// 点位选择处理
	const selectPoint = (point) => {
		selectedPoint.value = selectedPoint.value?.id === point.id ?
			null :
			point;
	};
	// 添加resize监听
	onMounted(() => {
		window.addEventListener('resize', handleResize);
	});

	// 移除监听
	onUnmounted(() => {
		window.removeEventListener('resize', handleResize);
	});
	// 判断特殊点位
	const isSpecialPoint = (point) => {
		return point.id === startPoint.value?.id ||
			point.id === endPoint.value?.id;
	};

	// 设置起点终点
	const setAsStart = () => {
		startPoint.value = selectedPoint.value;
		ElMessage.success(`已设置起点：${selectedPoint.value.pointName}`);
	};

	const setAsEnd = () => {
		endPoint.value = selectedPoint.value;
		ElMessage.success(`已设置终点：${selectedPoint.value.pointName}`);
	};
	// 路径规划处理
	const handlePathPlanning = async () => {
		try {
			isLoading.value = true;
			abortController.value = new AbortController();
			console.log('发起调度请求');
			const response = await axios.post('/device/dispatch', {
				start: startPoint.value,
				end: endPoint.value
			}, {
				signal: abortController.value.signal
			});
			pathPoints.value = response.data.map(p => ({
				x: Number(p.locationX),
				y: Number(p.locationY)
			}));
			ElMessage.success('路径规划成功');
		} catch (error) {
			if (!axios.isCancel(error)) {
				ElMessage.error('路径规划失败');
				console.error('路径规划错误:', error);
			}
		} finally {
			isLoading.value = false;
			abortController.value = null;
		}
	};
	// 更新路径计算
	const pathData = computed(() => {
		if (pathPoints.value.length === 0) return '';
		return pathPoints.value
			.map((p, i) => `${i === 0 ? 'M' : 'L'} ${p.x} ${p.y}`)
			.join(' ');
	});
	// 清空起终点
	const clearPoints = () => {
		startPoint.value = null;
		endPoint.value = null;
		pathPoints.value = [];
		ElMessage.info('已清空起终点');
	};

	// 取消路径规划
	const cancelPathPlanning = () => {
		if (abortController.value) {
			abortController.value.abort();
			ElMessage.warning('已取消路径规划');
		}
		isLoading.value = false;
		pathPoints.value = [];
	};

	// 修改模拟数据生成（添加pointType）
	const generateMockData = () => {
		return [{
				id: 1,
				x: 100,
				y: 100,
				pointType: 'CAR',
				pointName: '车辆点位'
			},
			{
				id: 2,
				x: 200,
				y: 150,
				pointType: 'WAREHOUSE',
				pointName: '仓库点位'
			},
			{
				id: 3,
				x: 300,
				y: 300,
				pointType: 'TRANSFER',
				pointName: '转折点位'
			}
		];
	};

	// 路径生成计算属性
	const loadpathData = computed(() => {
		if (points.value.length === 0) return '';
		return points.value
			.map((p, i) => `${i === 0 ? 'M' : 'L'} ${p.x} ${p.y}`)
			.join(' ');
	});

	const fetchPoints = async () => {
		try {
			let response = await axios.post('/points/getAll'); // 替换为实际的 API 地址
			console.log('加载点位个数:' + response.data.length);
			if (!Array.isArray(response.data)) {
				throw new Error(`无效的响应类型，预期数组，实际得到: ${typeof response.data}`);
			}
			// 数据转换
			let validPoints = response.data
				.map(p => ({
					id: Number(p.id),
					pointName: p.pointName || '未命名',
					pointType: p.pointType || 'DEFAULT',
					x: Number(p.locationX) || 0,
					y: Number(p.locationY) || 0,
					nodeId: p.nodeId
				}))
				.filter(p => Number.isInteger(p.id) && p.id > 0);
			// 更新状态
			points.value = validPoints;
		} catch (error) {
			console.log('加载失败:', error);
			ElMessage.error(`加载失败,仅展示默认的点位示例`);
			points.value = [{
					id: 1,
					x: 100,
					y: 100,
					pointType: 'CAR',
					pointName: '车辆点位'
				},
				{
					id: 2,
					x: 200,
					y: 150,
					pointType: 'WAREHOUSE',
					pointName: '仓库点位'
				},
				{
					id: 3,
					x: 300,
					y: 300,
					pointType: 'TRANSFER',
					pointName: '旋转点位'
				}
			];
		}
	};

	// 组件挂载时获取初始数据
	onMounted(() => {
		document.title = '调度服务页面';
		fetchPoints()
	})
	// 组件卸载时取消请求
	onUnmounted(() => {
		if (abortController.value) {
			abortController.value.abort();
		}
	});
</script>

<style scoped>

</style>